import qrcode
from io import BytesIO
from typing import Any, Dict
from alipay import AliPay

from config.dev import ALIPAY_CONFIG


class AlipayService:
    """支付宝支付服务"""
    def __init__(self):
        
        # 读取私钥文件内容
        with open(ALIPAY_CONFIG["app_private_key_path"], "r") as f:
            self.app_private_key_string = f.read()  # 定义为实例属性
            # print('应用私钥',self.app_private_key_string)
        
        # 读取支付宝公钥证书文件内容
        with open(ALIPAY_CONFIG["alipay_public_key_path"], "r") as f:
            self.alipay_public_key_string = f.read()  # 定义为实例属性
            
        try:   
            # 初始化支付宝客户端
            self.alipay = AliPay(
                appid=ALIPAY_CONFIG["appid"],
                app_private_key_string=self.app_private_key_string,  # 使用实例属性
                alipay_public_key_string=self.alipay_public_key_string,  # 使用实例属性
                sign_type=ALIPAY_CONFIG["sign_type"],
                debug=ALIPAY_CONFIG["debug"]
            )
        except FileNotFoundError:
            print("证书文件未找到，请检查文件路径")
        except Exception as e:
            print(f"初始化支付宝客户端时发生错误: {e}")
    
    def create_payment(self, out_trade_no: str, total_amount: float, subject: str) -> str:
        """生成支付链接"""
        order_string = self.alipay.api_alipay_trade_page_pay(
            out_trade_no=out_trade_no,
            total_amount=total_amount,
            subject=subject,
            return_url=ALIPAY_CONFIG["return_url"],
            notify_url=ALIPAY_CONFIG["notify_url"]
        )
        return f"https://openapi-sandbox.dl.alipaydev.com/gateway.do?{order_string}"


    def query_payment(self, out_trade_no: str) -> Dict[str, Any]:
        """查询支付结果"""
        result = self.alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
        return result

    def verify_notification(self, data: Dict[str, Any]) -> bool:
        """验证支付宝异步通知签名"""
        # 提取签名
        signature = data.pop("sign", None)
        if not signature:
            return False
        
        # 使用SDK验证签名（自动处理证书链验证）
        return self.alipay.verify(data, signature)

# if __name__ == "__main__":
#     alipay_service = AlipayService()
#     print(alipay_service.create_payment("ORDER20230615001", 99.00, "测试商品"))


    
    